#!/usr/bin/env python
# coding: utf-8

# In[ ]:


import os
import cv2
from PIL import Image


# In[1]:


def resize_img(DATADIR, data_k, img_size):
    w = img_size[0]
    h = img_size[1]
    path = os.path.join(DATADIR, data_k)
    #返回path路径下所有文件的名字，以及文件夹的名字，
    img_list = os.listdir(path)
    
 
    for i in img_list:
        if i.endswith('.jpg'):
            # 调用cv2.imread读入图片，读入格式为IMREAD_COLOR
            img_array = cv2.imread((path + '/' + i), cv2.IMREAD_COLOR)
            # 调用cv2.resize函数resize图片
            new_array = cv2.resize(img_array, (w, h), interpolation=cv2.INTER_CUBIC)
            img_name = str(i)
            '''生成图片存储的目标路径'''
            save_path = path + '_new/'
            if os.path.exists(save_path):
                print(i)
                '''调用cv.2的imwrite函数保存图片'''
                save_img=save_path+img_name
                cv2.imwrite(save_img, new_array)
            else:
                os.mkdir(save_path)
                save_img = save_path + img_name
                cv2.imwrite(save_img, new_array)
 


# In[4]:


def image_binarization(DATADIR, data_k):
        # 将图片转为灰度图
    path = os.path.join(DATADIR, data_k)
    #print(path)
    
    img_list = os.listdir(path)
    for image_file in img_list:
        img = Image.open(DATADIR+'\\'+data_k+'\\'+image_file)
        img=img.convert('1')
        
        #ray = cv2.cvtColor(image_file, cv2.COLOR_BGR2GRAY)
            # retval, dst = cv2.threshold(gray, 110, 255, cv2.THRESH_BINARY)
            # 最大类间方差法(大津算法)，thresh会被忽略，自动计算一个阈值
        #etval, dst = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)
        
        

        save_path = path + '_binary'
        bin_file=os.path.splitext(image_file)[0]
        if os.path.exists(save_path):
            #rint(i)
            img.save(save_path+'\\'+bin_file+'.png')
        else:
            os.mkdir(save_path)
            img.save(save_path+'\\'+bin_file+'.png')


# In[ ]:




